{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 应用于机器学习模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer\n",
    "from sklearn.svm import LinearSVC\n",
    "from sklearn.datasets import fetch_20newsgroups\n",
    "\n",
    "categories = ['alt.atheism', 'soc.religion.christian', 'comp.graphics', 'sci.med']\n",
    "remove = ('headers', 'footers', 'quotes')\n",
    "twenty_train = fetch_20newsgroups(subset='train', \n",
    "                                  remove=remove, \n",
    "                                  categories=categories) # 训练数据\n",
    "twenty_test = fetch_20newsgroups(subset='test',\n",
    "                                 remove=remove, \n",
    "                                 categories=categories) # 验证数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.7423435419440746"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "count_vect = CountVectorizer() # 单词出现次数\n",
    "X_train_counts = count_vect.fit_transform(twenty_train.data)\n",
    "X_test_count = count_vect.transform(twenty_test.data)\n",
    "\n",
    "model = LinearSVC() \n",
    "model.fit(X_train_counts, twenty_train.target)\n",
    "predicted = model.predict(X_test_count)\n",
    "np.mean(predicted == twenty_test.target)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.8149134487350199"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "tf_vec = TfidfVectorizer()  # tf-idf\n",
    "X_train_tfidf = tf_vec.fit_transform(twenty_train.data)\n",
    "X_test_tfidf = tf_vec.transform(twenty_test.data)\n",
    "\n",
    "model = LinearSVC()\n",
    "model.fit(X_train_tfidf, twenty_train.target)\n",
    "predicted = model.predict(X_test_tfidf)\n",
    "np.mean(predicted == twenty_test.target)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
